﻿package com.eshore.player;

import android.util.Log;


public class PlayerIsReadyThread extends Thread {

	ImagePlayerViewRtmp view = null;
	boolean isRunning = false;

	public PlayerIsReadyThread(ImagePlayerViewRtmp view) {
		this.view = view;
	}

	@Override
	public synchronized void run() {
		int returnvalue = 0;
		Log.d("ImagePlayer", "ffplay check Ready");
		isRunning = true;
		while (returnvalue != 1 && isRunning) {
			try {
				returnvalue = ImagePlayerView.ffplayIsReady();
			} catch (Exception e) {
				returnvalue = 0;
			}
			try {
				sleep(10);
			} catch (InterruptedException e) {
				Log.d("ImagePlayer", "ffplay IsReady canceled.");
				this.pause();
				return;
			}
			if (returnvalue != 1) {
				Log.d("ImagePlayer",
							"ffplay Isnot Ready, wait 0.5 second...");
				try {
					sleep(500);
				} catch (InterruptedException e) {
					Log.d("ImagePlayer", "ffplay IsReady canceled.");
					this.pause();
					return;
				}
				continue;
			}
		}
		// 取图片大小
		int cGetImageWidth = 0;
		int cGetImageHeight = 0;

		try {
			cGetImageWidth = ImagePlayerView.ffplayImageWidth();
		} catch (Exception e) {
			cGetImageWidth = 320;
		}
		try {
			sleep(10);
		} catch (InterruptedException e) {
			Log.d("ImagePlayer",
						"ffplay IsReady canceled on get image size.");
			this.pause();
			return;
		}
		try {
			if (this.view == null) {
				this.pause();
				return;
			} else {
				this.view.setcGetImageWidth(cGetImageWidth);
			}
			try {
				cGetImageHeight = ImagePlayerView.ffplayImageHeight();
			} catch (Exception e) {
				cGetImageHeight = 240;
			}
			this.view.setcGetImageHeight(cGetImageHeight);
			// 开始显示
			if (isRunning) {

				if (this.view == null) {
					this.pause();
					return;
				} else {
					this.view.startPlayDrawImageThread();
				}
			}
		} catch (Exception e) {
			this.pause();
			return;
		}
	}

	public void pause() {
		isRunning = false;
		this.view = null;
		try {
			ImagePlayerView.ffplayStop();
		} catch (Exception e) {

		}
		// int returnvalue = 0;
		// try {
		// returnvalue = ImagePlayerView.ffplayStop();
		// } catch (Exception e) {
		// returnvalue = 1;
		// }
		// if (returnvalue != 0) {
		// IshowEvList.d("ImagePlayer", "ffplay cannot stop");
		// // return;
		// }
	}

	@Override
	public synchronized void start() {
		super.start();
	}

}
